{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math, os\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from tqdm import tqdm\n",
    "from collections import *\n",
    "import itertools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "path = os.path.expanduser(\"~/blob/raw_datasets/steam/chatbot/user_history.tsv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_data = pd.read_csv(path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>user_id</th>\n",
       "      <th>item_id</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   user_id  item_id\n",
       "0        1        1\n",
       "1        1        2\n",
       "2        1        3"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train_data.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "history = train_data.groupby('user_id').agg(list)\n",
    "uidict = history.to_dict()['item_id']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def itemCFTrain(df):\n",
    "    \n",
    "    #create list for dict\n",
    "    user_item_list = []\n",
    "    for idx, row in tqdm(df.iterrows(), total=df.shape[0]):\n",
    "        user = (row['user_id'])\n",
    "        item = (row['item_id'])\n",
    "        user_item_list.append([user, item])\n",
    "    \n",
    "    #create dict\n",
    "    user_item_dict = dict()\n",
    "    for user, item in tqdm(user_item_list):\n",
    "        user_item_dict.setdefault(user, list()) # changge set() to list()\n",
    "        user_item_dict[user].append(item)\n",
    "    \n",
    "    return user_item_dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def ItemMatrix_fn(user_item_dict):\n",
    "    \n",
    "    N = defaultdict(int)\n",
    "    itemMatrix = defaultdict(int)\n",
    "    for user, items in tqdm(user_item_dict.items()):\n",
    "        for i in items:\n",
    "            itemMatrix.setdefault(i, dict())\n",
    "            N[i] += 1\n",
    "            for j in items:\n",
    "                itemMatrix[i].setdefault(j, 0)\n",
    "                #if i==j:\n",
    "                #    continue\n",
    "                itemMatrix[i][j] += 1\n",
    "    \n",
    "    return itemMatrix, N\n",
    "\n",
    "def ItemMatrix_fn2(n_item, user_item_dict):\n",
    "    itemMatrix = np.zeros((n_item, n_item))\n",
    "    # cosine sim\n",
    "    for user, items in tqdm(user_item_dict.items()):\n",
    "        if len(items) <= 1:\n",
    "            print('user=', user)\n",
    "            continue\n",
    "        pairs = list(itertools.combinations(items, 2))\n",
    "        x1, x2 = zip(*pairs)\n",
    "        itemMatrix[x1,x2] += 1\n",
    "        itemMatrix[x2,x1] += 1\n",
    "    \n",
    "    return itemMatrix"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def ItemSimilarityMatrix_fn(ItemMatrix, N, normalize:bool=True):\n",
    "    \n",
    "    itemSimMatrix = defaultdict(int)\n",
    "    # cosine sim\n",
    "    \n",
    "    for i, related_items in tqdm(ItemMatrix.items()):\n",
    "        itemSimMatrix.setdefault(i, dict())\n",
    "        for j, cij in related_items.items():\n",
    "            itemSimMatrix[i].setdefault(j, 0)\n",
    "            itemSimMatrix[i][j] = cij / math.sqrt(N[i] * N[j])\n",
    "    \n",
    "    # normalization\n",
    "    if normalize:\n",
    "        for i, relations in tqdm(itemSimMatrix.items()):\n",
    "            max_num = relations[max(relations, key=relations.get)]\n",
    "            if max_num == 0:\n",
    "                continue\n",
    "            itemSimMatrix[i] = {k : v / max_num for k, v in relations.items()}\n",
    "    \n",
    "    return itemSimMatrix\n",
    "\n",
    "\n",
    "def ItemSimilarityMatrix_fn2(ItemMatrix):\n",
    "    \n",
    "    N = ItemMatrix.sum(axis=0)\n",
    "    N_ = np.sqrt(np.outer(N,N)) + 1e-10\n",
    "    # cosine sim\n",
    "    sim = ItemMatrix / (N_  + 1e-10)\n",
    "    \n",
    "    return sim"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 281204/281204 [01:18<00:00, 3591.81it/s] \n"
     ]
    }
   ],
   "source": [
    "n_items = train_data['item_id'].max() + 1\n",
    "itemMatrix = ItemMatrix_fn2(n_items, uidict)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(itemMatrix.sum(0) - itemMatrix.sum(1)).sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "item_cf_m = ItemSimilarityMatrix_fn2(itemMatrix)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "item_sim = item_cf_m.astype(np.float16)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.save(os.path.expanduser(\"~/blob/raw_datasets/steam/chatbot/item_sim.npy\"), item_sim)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llm4crs",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
